import { useDispatch, useSelector } from "react-redux"
import { setTabsList } from "@/redux/modules/tabs"
import { useLocation, useNavigate } from "react-router-dom"
import { commonRouterList } from "@/routers/routeList"
import { searchRoute } from "@/utils/utils"
import React, { useEffect, useState } from "react"
import { Tabs } from "antd"
import { HOME_URL } from "@/config/config"
import "./index.less"
import { State } from "@/redux/interface"

const LayoutTabs = () => {
    const dispatch = useDispatch()
    const { tabsList } = useSelector((state:State) => state.tabs)
    const { pathname } = useLocation()
    const navigate = useNavigate()
    const [activeValue, setActiveValue] = useState(pathname)

    useEffect(() => {
        addTabs()
    }, [pathname])

    const addTabs = () => {
        const route = searchRoute(pathname, commonRouterList)
        let newTabsList = JSON.parse(JSON.stringify(tabsList))
        if(tabsList.every((item:Menu.MenuOptions) => item.path !== route.path) && (route.path !== HOME_URL)) {
            newTabsList.push({title: route?.meta?.title, path: route.path})
        }
        dispatch(setTabsList(newTabsList))
        setActiveValue(pathname)
    }

    const delTabs = (path: React.MouseEvent | React.KeyboardEvent | string) => {
        if(pathname === path) {
            let index = tabsList.findIndex((item:Menu.MenuOptions) => item.path === path)
            if(tabsList.length > 1) {
                if(tabsList[index + 1]) {
                    navigate(tabsList[index + 1].path)
                }else{
                    navigate(tabsList[index - 1].path)
                }
            }else{
                navigate(HOME_URL)
            }
        }
        dispatch(setTabsList(tabsList.filter((item:Menu.MenuOptions) => item.path !== path)))
    }

    const clickTabs = (path:string) => {
        navigate(path)
    }

    return (
        <div className="tabs">
            <Tabs
                activeKey={activeValue}
                onChange={clickTabs}
                hideAdd
                type="editable-card"
                onEdit={delTabs}
                items={
                [
                    {
                        label:'首页',
                        key:HOME_URL,
                        closable: false
                    },
                    ...tabsList.map((item:Menu.MenuOptions) => {
                        return {
                            label: item.title,
                            key: item.path
                        }
                    })
                ]
            }/>
        </div>
    )
}

export default LayoutTabs